import requests
import time

class SaveSystem:
    def __init__(self):
        self.last_save_time = time.time()
        self.save_interval = 5  # 5秒保存一次
        self.current_username = None
        
    def set_username(self, username):
        self.current_username = username
        
    def should_save(self):
        current_time = time.time()
        if current_time - self.last_save_time >= self.save_interval:
            self.last_save_time = current_time
            return True
        return False
        
    def save_game(self, player_sprite, inventory, storage):
        if not self.current_username:
            return False
            
        try:
            response = requests.post(
                "http://localhost:5000/save_game",
                json={
                    "username": self.current_username,
                    "game_data": {
                        "current_hp": player_sprite.current_hp,
                        "inventory": [{
                            'name': sprite.name,
                            'max_hp': sprite.max_hp,
                            'attack': sprite.attack,
                            'defense': sprite.defense,
                            'speed': sprite.speed
                        } for sprite in inventory.sprites],
                        "eggs": [{
                            'name': egg.name,
                            'max_hp': egg.max_hp,
                            'attack': egg.attack,
                            'defense': egg.defense,
                            'speed': egg.speed,
                            'hatch_time': hatch_time
                        } for egg, hatch_time in storage.eggs if egg]
                    }
                }
            )
            return response.json()["success"]
        except Exception as e:
            print(f"Save game failed: {str(e)}")
            print(f"Error type: {type(e)}")  # 添加更详细的错误信息
            print(f"Current username: {self.current_username}")
            return False